package httpserver

import (
	"gluenet/internal/agent/api"
	"gluenet/internal/agent/service/prometheussvc"
	v1 "gluenet/pkg/log/v1"
	"io"
	"net/http"
)

const (
	prometheus = `prometheus`
)

func init() {
	registerRouter(api.HTTP_SERVICE_PROMETHEUS, NewPromethusRouter)
}

type prometheusRouter struct {
	svc *prometheussvc.Service
	log v1.Logger
}

func NewPromethusRouter(mux *http.ServeMux) {
	logger := v1.NewLogger(prometheus)
	svc := prometheussvc.NewService(logger)
	r := &prometheusRouter{
		svc: svc,
		log: logger,
	}
	mux.HandleFunc(api.WriteMetric, r.writeMetric)
}

func (rt *prometheusRouter) writeMetric(w http.ResponseWriter, r *http.Request) {
	data, err := io.ReadAll(r.Body)
	if err != nil {
		rt.log.Errorf("read request body error")
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	rt.svc.WriteMetric(data)
	w.WriteHeader(http.StatusNoContent)
}
